package com.learn.security.service.impl;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.result.Result;
import com.learn.result.ResultUtils;
import com.learn.security.config.props.JwtProperties;
import com.learn.security.mapper.UserMapper;
import com.learn.security.pojo.po.User;
import com.learn.security.pojo.vo.LoginUser;
import com.learn.security.pojo.vo.LoginVO;
import com.learn.security.service.UserService;
import com.learn.util.JwtUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
    
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtProperties jwtProperties;
    
    @Override
    public Result<LoginVO> login(User user) {
        // 封装Authentication对象
        UsernamePasswordAuthenticationToken authentication = 
            new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        //
        Authentication authenticate = authenticationManager.authenticate(authentication);
        if(Objects.isNull(authenticate)){
             throw new RuntimeException("用户名或密码错误");
        }
        Object principal = authenticate.getPrincipal();
        if(principal instanceof LoginUser){
            LoginUser loginUser = (LoginUser) principal;
            String info = JSON.toJSONString(loginUser); 
            String token = JwtUtil.sign(
                loginUser.getUsername(), 
                info, 
                jwtProperties.getExpiration(), 
                jwtProperties.getSecret()
            );
            LoginVO loginVO = new LoginVO();
            loginVO.setToken(token);
            return ResultUtils.success(loginVO);
        }else{
            throw new RuntimeException("用户信息错误");
        }
    }
    
}
